<?php
	// check params size and name
	if (!array_key_exists('un', $_POST))
	{
		echo "Usage";
		exit;
	}

	// if passed then define vars and connect to db
	$un = $_POST['un'];
	$mysqli = new mysqli('localhost', 'root', 'project3', 'server2');
	if ($mysqli->connect_errno)
	{
		echo "db connection error!";
		exit;
	}

	// if passed then get id and key
	$res = $mysqli->query("select * from ia_cred");
	if (!$res)
	{
		$mysqli->close();
		echo 9;
		exit;
	}
	$ob = $res->fetch_object();
	$id = $ob->id;
	$key = $ob->secretkey;

	// if passed then http to IAS
	$x = 0;
	do 
	{
		$code = sha1(time() . rand() . rand());
		$url = "http://173.1.2.194/restoreAccount.php?";
		$url .= "id=" . $id ;
		$url .= "&key=" . $key;
		$url .= "&hun=" . sha1($un);
		$url .= "&code=" . $code;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec($ch);
		curl_close($ch);
	} while ($result == '1' && $x++ < 10);
	if ($result != '0')
	{
		echo $result;
		$mysqli->close();
		exit;
	}
	
	// if passed then email and echo 0 
//////////// uncomment the line below to send mail
	sendCode($mysqli, $un, $code);
	echo 0;
	$mysqli->close();
	exit;


	/////////////////////////////////////////////////
	function sendCode($mysqli, $un, $code)
	{
		require_once "Mail.php";
		$from = "server2.IAS";
		$to = ""; // needs to be HERE!
		$subject = "Your IA account restoration code";
		$host = "ssl://smtp.gmail.com";
		$port = "465";
		$username = "cs249project3"; 
		$password = "project3";
		
		$res = $mysqli->query("select * from users where un like '$un'");
		$ob = $res->fetch_object();
		$otptype = $ob->otppref;
		if ($otptype == 'e')
		{
			if ($ob->email == null)
			{
				echo "Error! Email required for 2FA!";
				$res->close();
				exit();
			}
			$to = $ob->email;
			$res->close();
		}	
		else
		{
			if ($ob->phone == null)
			{
				echo "Error! Phone number required for 2FA!";
				$res->close();
				exit();
			}
			$to = $ob->phone;
			$res->close();
		}	

		$body = "Your IA account restoration code is: \n\n$code\n\nIf you have changed your mind, you can ignore this message and your account will stay intact.\nIf you still want to restore your IA account then please enter this code into your IA app on the new device.";
		$headers = array ('From' => $from,
		'To' => $to,
		'Subject' => $subject);
		$smtp = Mail::factory('smtp',
		array ('host' => $host,
		  'port' => $port,
		  'auth' => true,
		  'username' => $username,
		  'password' => $password));
		$mail = $smtp->send($to, $headers, $body);

		if (PEAR::isError($mail)) 
		{
			echo("Error: cannot send mail!");
			$mysqli->close();
			exit();
		} 
	}	
?>
